import logging
import time
import traceback
from contextlib import asynccontextmanager
from typing import Optional

from fastapi import FastAPI, Request, HTTPException, Depends, Header

from app.core.config import settings
from app.providers.writifyai_provider import WritifyAIProvider
from app.providers.worker_manager import worker_manager

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

@asynccontextmanager
async def lifespan(app: FastAPI):
    # 应用启动时
    logger.info("应用启动中...")
    await worker_manager.initialize()
    yield
    # 应用关闭时
    logger.info("应用关闭中...")
    await worker_manager.close()

app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    description=settings.DESCRIPTION,
    lifespan=lifespan
)

provider = WritifyAIProvider()

async def verify_api_key(authorization: Optional[str] = Header(None)):
    """验证 API 密钥的依赖项。"""
    if settings.API_MASTER_KEY:
        if not authorization or "bearer" not in authorization.lower():
            raise HTTPException(status_code=401, detail="需要 Bearer Token 认证。")
        token = authorization.split(" ")[-1]
        if token != settings.API_MASTER_KEY:
            raise HTTPException(status_code=403, detail="无效的 API Key。")

@app.post("/v1/chat/completions", dependencies=[Depends(verify_api_key)])
async def chat_completions(request: Request):
    """处理聊天请求。"""
    try:
        request_data = await request.json()
        return await provider.chat_completion(request_data, request)
    except Exception as e:
        logger.error(f"处理聊天请求时发生顶层错误: {e}")
        traceback.print_exc()
        raise HTTPException(status_code=500, detail=f"内部服务器错误: {e}")

@app.get("/v1/models", dependencies=[Depends(verify_api_key)])
async def list_models():
    """返回已知的模型列表。"""
    return {
        "object": "list",
        "data": [{"id": name, "object": "model", "created": int(time.time()), "owned_by": "system"} for name in settings.KNOWN_MODELS]
    }

@app.get("/status", dependencies=[Depends(verify_api_key)])
async def get_status():
    """获取 Worker 管理器的状态。"""
    return await worker_manager.get_status()

@app.get("/")
def root():
    """根路由，提供服务基本信息。"""
    return {"message": f"欢迎来到 {settings.APP_NAME} v{settings.APP_VERSION}"}
